﻿using System;
using Core.AdminGroup;
using Core.Authenticated;
using Core.Library;

namespace CMS.Controls.AdminGroup
{
    public partial class CreateOrEdit : AuthenticatedControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ltTitle.Text = "Tạo mới nhóm";

                if (Request.QueryString[Utils.GroupId] != null)
                {
                    var groupId = Utils.GetIdFromRequestString(Utils.GroupId, 0);

                    if (groupId > 0)
                    {
                        ltTitle.Text = "Sửa thông tin nhóm";

                        BindGroup(groupId);
                    }
                }
            }
        }

        private void BindGroup(int id)
        {
            var group = AdminGroupController.AdminGroup_GetById(id);
            if (group != null)
            {
                txtName.Text        = group.Name;
                txtDescription.Text = group.Description;
                txtPriority.Text    = group.Priority.ToString();
                hfStatus.Value      = group.Status.ToString();
            }
        }

        protected void Save(object sender, EventArgs e)
        {
            AdminGroupObject o;

            var id = Utils.GetIdFromRequestString(Utils.GroupId, 0);

            if (id > 0)
            {
                o = AdminGroupController.AdminGroup_GetById(id);
                o.AdminGroupId  = id;
                o.Name          = txtName.Text;
                o.Description   = txtDescription.Text;
                o.Priority      = ConvertUtility.ToInt32(txtPriority.Text);
                o.Status        = ConvertUtility.ToInt32(hfStatus.Value);

                AdminGroupController.AdminGroup_Update(o);
            }
            else
            {
                o = new AdminGroupObject();
                o.Name          = txtName.Text;
                o.Description   = txtDescription.Text;
                o.Priority      = ConvertUtility.ToInt32(txtPriority.Text);
                o.Status        = ConvertUtility.ToInt32(hfStatus.Value);

                AdminGroupController.AdminGroup_Create(o);
            }

            Response.Redirect(UrlHelpers.ListGroup);
        }
    }
}